package kr.saeildamil.androidStudy_second.gesture;

import kr.saeildamil.androidStudy_second.R;
import android.app.Activity;
import android.graphics.Matrix;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.ImageView;
import android.widget.TextView;

public class PinchZoom extends Activity {
	final static float STEP = 200;
	TextView mTxtRatio;
	float mRatio = 1.0f;
	int mBaseDist;
	float mBaseRatio;
	ImageView mImg;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch31_pinchzoom);

		mTxtRatio = (TextView) findViewById(R.id.ratio);
		mTxtRatio.setText(Float.toString(mRatio));
		mImg = (ImageView) findViewById(R.id.img);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getPointerCount() == 2) {
			int action = event.getAction();
			int pureaction = action & MotionEvent.ACTION_MASK;

			if (pureaction == MotionEvent.ACTION_POINTER_DOWN) {
				mBaseDist = getDistance(event);
				mBaseRatio = mRatio;
			} else {// 손가락을 벌렸을때 또는 줄였을때
				float delta = (getDistance(event) - mBaseDist) / STEP;
				float multi = (float) Math.pow(2, delta);
				mRatio = Math.min(1024f, Math.max(0.1f, mBaseRatio) * multi);
				mTxtRatio.setText(String.format("%.2f", mRatio));

				Matrix m = new Matrix();
				m.postScale(mRatio, mRatio);
				mImg.setImageMatrix(m);
			}
		}
		return true;

	}

	int getDistance(MotionEvent event) {
		int dx = (int) (event.getX(0) - event.getX(1));
		int dy = (int) (event.getY(0) - event.getY(1));

		return (int) (Math.sqrt(dx * dx + dy * dy));

	}
}
